import java.util.concurrent.BlockingQueue;

class MyBlockingQueue {
    public String[] elems = null;

    public MyBlockingQueue(int capacity) {
        elems = new String[capacity];
    }

    public Object locker = new Object();
    public int size;
    public int head;
    public int tail;

    public void put(String elem) throws InterruptedException {
        synchronized (locker) {
            while (size >= elems.length) {  //使用wait是不推荐使用if
                locker.wait();              //if 执行一次会立即释放，后续不满足条件还是会执行
            }
            elems[tail] = elem;
            tail++;
            if (tail >= elems.length) {
                tail = 0;
            }
            size++;
            locker.notify();//入队列之后有元素时进行唤醒
        }
    }

    public String take() throws InterruptedException {
        String elem = null;
        synchronized (locker) {
            while (size == 0) {
                locker.wait();
            }
            elem = elems[head];
            head++;
            if (head >= elems.length) {
                head = 0;
            }
            size--;
            locker.notify(); //当有元素出队列时，对进队列的操作进行唤醒
        }
        return elem;
    }
}
    public class ThreadDemo24 {
        public static void main(String[] args) throws InterruptedException {
            MyBlockingQueue queue = new MyBlockingQueue(1000);
//            queue.put("aaa");
//            queue.put("bbb");
//            queue.put("ccc");
//            queue.put("ddd");
//
//            String elem = "";
//            elem = queue.take();
//            System.out.println("elem: " + elem);
//            elem = queue.take();
//            System.out.println("elem: " + elem);
//            elem = queue.take();
//            System.out.println("elem: " + elem);
//            elem = queue.take();
//            System.out.println("elem: " + elem);
            Thread t1 = new Thread(() ->{
                int n = 1;
                while (true){
                    try {
                        queue.put(n + "");
                        System.out.println("生产元素 "+ n);
                        n++;
//                        Thread.sleep(1000);
                        //当生产者进行等待时，可以变相说明生产者生产的慢
                        //此时要进行消费的话，消费者也需要等待生产者的生产
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                }
            });
            Thread t2 = new Thread(() ->{
               while (true){
                   try {
                       String elem = queue.take();
                       System.out.println("消费者元素"+ elem);
                       Thread.sleep(1000);
                   } catch (InterruptedException e) {
                       throw new RuntimeException(e);
                   }
               }
            });
            t1.start();
            t2.start();
        }
    }
